package com.ckr.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author Shadowckr
 * @create 2022-01-17 11:47
 */

@Controller
public class MyController {

    @RequestMapping({"/", "/index"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello, Shiro!");
        return "index";
    }

    @RequestMapping("/user/add")
    public String add() {
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String toUpdate() {
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    //登录操作
    //参考Quickstart.java
    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        //使用shiro，编写认证操作
        //1. 获取Subject(currentUser)
        Subject currentUser = SecurityUtils.getSubject();
        //2. 封装用户的数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //3. 执行登录的方法，只要没有异常就代表登录成功！
        try {
            currentUser.login(token); //登录成功！返回首页
            return "index";
        } catch (UnknownAccountException e) { //用户名不存在
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) { //密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @RequestMapping("/unauthorized")
    @ResponseBody
    public String unAuth() {
        return "未经授权不能访问此页面！";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
//        session.invalidate();
        session.removeAttribute("loginUser");
        return "login";
    }

}
